#include "localuserwidget.h"
#include "actionmanager.h"
#include "libs/core/user/localuser.h"
#include "usersettings.h"
#include "utils/utils.h"
#include "yingce.h"
#include <QMenu>

LocalUserWidget::LocalUserWidget(QWidget* parent) : QPushButton(parent)
{
    setFlat(true);
    updateUi();

    yc::LocalUser* user = YingCe::instance()->localUser();
    Q_ASSERT(user);
    connect(user, &yc::LocalUser::loginStatusChanged, this, &LocalUserWidget::updateUi);
    connect(user, &yc::LocalUser::nicknameChanged, this, &LocalUserWidget::updateUi);
    connect(user, &yc::LocalUser::avatarUrlChanged, this, &LocalUserWidget::updateUi);

    connect(this, &QPushButton::clicked, this, [this] {
        if (YingCe::instance()->localUser()->offline()) {
            YingCe::instance()->login();
        } else {
            QMenu* menu = ActionManager::instance()->buildAccountMenu(this);
            menu->ensurePolished();
            const QSize sz = size();
            int x = (sz.width() - menu->width()) / 2;
            int y = sz.height() + 2;
            menu->exec(mapToGlobal(QPoint(x, y)));
            menu->deleteLater();
        }
    });
}

void LocalUserWidget::updateUi()
{
    yc::LocalUser* user = YingCe::instance()->localUser();
    if (user->offline()) {
        setText(tr("Click to login"));
        setIcon(QIcon(":/images/user.png"));
    } else {
        setText(user->displayName());
        if (user->avatar().isEmpty()) {
            setIcon(QIcon(":/images/user.png"));
        } else {
            const QString avatar_path =
                    UserSettings::instance().resDir().absoluteFilePath(user->avatar());
            if (QFileInfo::exists(avatar_path)) {
                setIcon(QIcon(utils::circlePixmap(avatar_path, QSize(32, 32))));
            } else {
                setIcon(QIcon(":/images/user.png"));
            }
        }
    }
}
